/* eslint-disable no-param-reassign */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Upload } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid } from '../stores/definitions';
import styles from './Announcement.module.scss';
import moment from 'moment';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 6,
  },
  wrapperCol: {
    span: 17,
  },
  style: { marginBottom: 20 },
};

function Announcement({ activity, modal, onSubmit, onCancel, handleCustomRequest }) {
  const { activityStore: store } = useStore();
  const [announcement] = useState(() => observable({}));
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  const uploaderRef = useRef();
  const [disabledAdd, setDisabledAdd] = useState(false);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (JSON.stringify(activity) !== '{}') {
      (async () => {
        const data = await store.get(activity?.id);
        const beginTime = data?.announcement?.beginTime || null;
        const endTime = data?.announcement?.endTime || null;
        editCtx.origin = _.cloneDeep(data);
        _.assign(announcement, data);
        setDisabledAdd(data?.announcement?.pictures?.length !== 0);
        _.set(announcement, 'announcement.timeRange', [moment(beginTime).add('8', 'hours').format('YYYY-MM-DD'), moment(endTime).add('8', 'hours').format('YYYY-MM-DD')]);
      })();
    }
  }, []);

  if (!announcement) return <></>;

  const overrideModel = {
    announcement: {
      pictures: {
        label: t`图片`,
        ui: {
          renderer: (r) => {
            return (
              <Upload.Card
                listType="card"
                className={disabledAdd ? styles.disabled_add : styles.container}
                value={r}
                name="announcement.pictures"
                autoUpload={false}
                beforeUpload={beforeUpload}
                headers={{ Authorization: `Bearer ${TOKEN}` }}
                data={(file) => {
                  return { binaryId: file.uid, mimeType: file.type };
                }}
                ref={saveUploaderRef}
                formatter={(res, files) => {
                  return {
                    uid: files.uid,
                    name: files.name,
                    state: 'done',
                    type: files.type,
                    url: `${API_BASE}/api/files/${files.uid}`,
                    downloadURL: `${API_BASE}/api/files/${files.uid}`,
                    imgURL: `${API_BASE}/api/files/${files.uid}`,
                  };
                }}
                onChange={handleUploadAdd}
                useDataURL
                request={handleCustomRequest}
                action={`${API_BASE}/upload`}
                accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp, image/webp"
              />
            );
          },
        },
      },
    },
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(announcement, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const saveUploaderRef = (ref) => {
    if (ref) uploaderRef.current = ref.getInstance();
  };

  const beforeUpload = (info, options) => {
    return options;
  };

  /**
   * @description 上传组件事件
   * @param {*} v
   */
  const handleUploadAdd = (v) => {
    if (v?.length >= 1) {
      setDisabledAdd(true);
    } else {
      setDisabledAdd(false);
    }
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: Announcement.jsx:137 _ errors:', errors);
      return;
    }
    const { pictures } = announcement.announcement;
    let img = [];
    if (pictures?.length > 0) {
      img = pictures.map((item) => ({
        name: item.name,
        type: item.type,
        uid: item.uid,
      }));
    }
    const [beginTime, endTime] = announcement?.announcement?.timeRange;
    _.set(announcement, 'announcement.beginTime', beginTime ? moment(beginTime).subtract('8', 'hours').toISOString() : '');
    _.set(announcement, 'announcement.endTime', endTime ? moment(endTime).subtract('8', 'hours').toISOString() : '');
    _.set(announcement, 'announcement.pictures', img);
    delete announcement.announcement.timeRange;
    onSubmit?.(announcement);
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={announcement}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
      style={{ marginTop: 20 }}
    >
      <FieldsGrid
        formData={announcement}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        mode={modal[0]}
        columns={1}
        overrideModel={overrideModel}
        fields={[
          'title', 'text', 'pictures', 'link', 'timeRange', 'enable', 'place', 'signState',
        ].map((p) => `announcement.${p}`)}
      />

      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>

    </Form>
  );
}

export default observer(Announcement);

